﻿using System;
using System.ComponentModel;
using System.Web;
using System.Globalization;

namespace TPG.SharePoint.Workflow
{
    internal static class QueryStringParser
    {
        internal static T GetParameter<T>(string name)
        {
            return GetParameter<T>(name, false);
        }

        internal static T GetParameterAllowNull<T>(string name)
        {
            return GetParameter<T>(name, true);
        }

        internal static T GetParameter<T>(string name,
            TypeConverter converter)
        {
            return GetParameter<T>(name, false, converter);
        }

        internal static T GetParameter<T>(string name, 
            bool allowNull)
        {
            return GetParameter<T>(name, allowNull, 
                TypeDescriptor.GetConverter(typeof(T)));
        }

        internal static T GetParameter<T>(string name, 
            bool allowNull, TypeConverter converter)
        {
            string valueString = HttpContext.Current.Request.Params[name];
            if (allowNull || !String.IsNullOrEmpty(name))
            {
                if (!converter.CanConvertFrom(null, typeof(String)))
                {
                    throw new WorkflowException(
                        string.Format(CultureInfo.CurrentCulture, "Specified TypeConverter cannot convert a System.String to {0}.",
                        typeof(T)));
                }
                try
                {
                    return (T)converter.ConvertFromInvariantString(valueString);
                }
                catch (NotSupportedException) { }
                catch (FormatException) { }
            }
            throw new WorkflowException(
                string.Format(CultureInfo.CurrentCulture, "Missing or invalid form parameter '{0}'", name));
        }
    }
}
